/**
 * 用户模型
 * Created by jinlei on 14-10-11.
 */

var bcrypt = require('bcrypt');

function hashPassword(values, next) {
  bcrypt.hash(values.password, 10, function(err, hash) {
    if (err) {
      return next(err);
    }
    values.password = hash;
    next();
  });
}

module.exports = {

  types:{
    description:function(value) {
      return true;
    },
    is_avatar:function(avatar) {
      return avatar.url && avatar.filePath;
    }
  },

  attributes: {
    username: {
      type: 'string',
      required: true,
      description: '用户名'
    },
    type: {
      type: 'string',
      required: true,
      enum: ['phone', 'email', 'name'],
      defaultsTo: 'name',
      description: '账号类型'
    },
    password: {
      type: 'string',
      required: true,
      description: '密码'
    },
    isAdmin: {
      type: 'bool',
        required: false,
        description: '是否是管理员'
    },
    avatar: {
      type: 'json',
      required: false,
      is_avatar:true,
      description: '用户头像'
    },
    nickname: {
      type: 'string',
      required: false,
      description: '昵称'
    },
    gender: {
      type: 'enum',
      required: false,
      enum:['male', 'female'],
      description: '性别'
    },
    introduction: {
      type: 'string',
      required: false,
      description: '个人简介'
    },

    // Override toJSON instance method to remove password value
    toJSON: function() {
      var obj = this.toObject();
      delete obj.password;
      return obj;
    },
    validPassword: function(password, callback) {
      var obj = this.toObject();
      if (callback) {
        return bcrypt.compare(password, obj.password, callback);
      }
      return bcrypt.compareSync(password, obj.password);
    }
  },

  beforeCreate: function(values, next) {
    hashPassword(values, next);
  },
  beforeUpdate: function(values, next) {
    if (values.password) {
      hashPassword(values, next);
    } else {
      next();
    }
  }
}